package com.natalia.excel.controller;

import com.natalia.excel.constants.BusinessConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;

import java.io.File;
import java.util.concurrent.TimeUnit;

/**
 * @Author yang
 **/
@Slf4j
@Validated
@RestController
@RequestMapping("/files")
@RequiredArgsConstructor
public class FileController {

    /**
     * 增加浏览器缓存的下载图片
     * 测试的时候注意浏览器是否禁用缓存
     * @param filename
     * @param request
     * @return
     */
    @GetMapping("{filename}")
    public ResponseEntity<InputStreamSource> download(@PathVariable("filename") String filename,
                                                      WebRequest request){
        File target = new File(BusinessConstants.LOCAL_PATH.concat(filename));
        long lastModified = target.lastModified();
        String eTag = BusinessConstants.FILE_SIZE;
        if (target.exists()) {
            String ext = filename.substring(filename.lastIndexOf(BusinessConstants.DROP) + 1);
            if (request.checkNotModified(eTag,lastModified)) {
                return ResponseEntity.status(HttpStatus.NOT_MODIFIED).build();
            }
            InputStreamSource resource = new FileSystemResource(target);
            return ResponseEntity.ok()
                    .eTag(eTag)
                    .cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS))
                    .lastModified(lastModified)
                     //比如video/mp4等，这时我们需要直接通过字符串设置响应头
                    .header(BusinessConstants.CONTENT_TYPE,
                            BusinessConstants.IMAGE_TYPE.concat(ext))
                    .body(resource);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}
